package com.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.ShopMapper;
import com.example.model.dto.CreateShopDTO;
import com.example.model.dto.Result;
import com.example.model.entity.Shop;
import com.example.model.vo.ShopDetailVO;
import com.example.model.vo.ShopVO;
import com.example.model.vo.ShopsVO;
import com.example.service.IShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: backend
 * @author: zk
 * @create: 2023-04-21 16:23
 **/
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Override
    public Result getShops(int pageNum, int pageSize) {
        // 1.查询范围商品
        int stat = (pageNum - 1) * pageSize + 1;
        int end = (pageNum - 1) * pageSize + 10;
        List<Shop> shopList = query().between("id", stat, end).list();

        if (shopList.size() == 0) {
            return Result.fail("没有咯！");
        }

        // 2.转换前端需要的商品信息
        List<ShopVO> shops = new ArrayList<>();
        for (Shop shop : shopList) {
            shops.add(BeanUtil.copyProperties(shop, ShopVO.class));
        }

        // 3，封装信息
        ShopsVO shopsVO = new ShopsVO();
        shopsVO.setList(shops);

        return Result.ok(shopsVO);
    }

    @Override
    public Result getShop(String productId) {
        if (Integer.parseInt(productId) <= 0) {
            return Result.fail("商品信息有误");
        }

        // 1.根据商品 id 查找商品信息
        Shop shop = query().eq("id", Integer.parseInt(productId)).one();

        // 2.未找到商品信息
        if (shop == null) {
            return Result.fail("该商品已下架或删除");
        }


        // 3.封装商品信息
        String size = shop.getSize();
        shop.setSize(null);
        String subImages = shop.getSubImages();
        shop.setSubImages(null);
        ShopDetailVO shopDetailVO = BeanUtil.copyProperties(shop, ShopDetailVO.class);


        if (size.length() != 0) {
            String[] strings = size.split(",");
            List<Double> list = new ArrayList<>();
            for (String string : strings) {
                list.add(Double.parseDouble(string));
            }
            shopDetailVO.setSize(list);
        }

        if (subImages.length() != 0) {
            String[] strings = subImages.split(",");
            List<String> list = new ArrayList<>(Arrays.asList(strings));
            shopDetailVO.setSubImages(list);
        }

        // 4.返回商品信息
        return Result.ok(shopDetailVO);
    }

    @Override
    public Shop getShopsById(Long id) {
        return query().eq("id", id).one();
    }

    @Override
    public Result saveShoeShop(CreateShopDTO shopDTO) {
        ;
        Shop shop = BeanUtil.copyProperties(shopDTO, Shop.class);

        save(shop);
        return Result.ok("保存成功");
    }
}
